package com.yuanqi.service.impl;

import com.yuanqi.domain.RetailReturnOrder;
import com.yuanqi.domain.OrderTracking;
import com.yuanqi.repository.RetailReturnOrderRepository;
import com.yuanqi.repository.OrderTrackingRepository;
import com.yuanqi.service.RetailReturnOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 零售退货订单服务实现类
 */
@Service
@Transactional
public class RetailReturnOrderServiceImpl implements RetailReturnOrderService {
    
    @Autowired
    private RetailReturnOrderRepository retailReturnOrderRepository;
    
    @Autowired
    private OrderTrackingRepository orderTrackingRepository;
    
    @Override
    public RetailReturnOrder createReturnOrder(RetailReturnOrder returnOrder) {
        // 生成退货单编码
        if (returnOrder.getReturnCode() == null || returnOrder.getReturnCode().isEmpty()) {
            returnOrder.setReturnCode(generateReturnCode());
        }
        
        returnOrder.setReturnDate(LocalDateTime.now());
        returnOrder.setCreatedAt(LocalDateTime.now());
        returnOrder.setUpdatedAt(LocalDateTime.now());
        
        RetailReturnOrder savedOrder = retailReturnOrderRepository.save(returnOrder);
        
        // 创建订单跟踪记录
        createOrderTracking(savedOrder.getId(), savedOrder.getReturnCode(), "Return", 
                           "Pending", "退货申请已提交", "系统", "退货申请创建成功");
        
        return savedOrder;
    }
    
    @Override
    public RetailReturnOrder updateReturnOrder(RetailReturnOrder returnOrder) {
        returnOrder.setUpdatedAt(LocalDateTime.now());
        return retailReturnOrderRepository.save(returnOrder);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<RetailReturnOrder> findById(Long id) {
        return retailReturnOrderRepository.findById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Optional<RetailReturnOrder> findByReturnCode(String returnCode) {
        return retailReturnOrderRepository.findByReturnCode(returnCode);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailReturnOrder> findAll() {
        return retailReturnOrderRepository.findAll();
    }
    
    @Override
    @Transactional(readOnly = true)
    public Page<RetailReturnOrder> findAll(Pageable pageable) {
        return retailReturnOrderRepository.findAll(pageable);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailReturnOrder> findByOriginalOrderId(Long originalOrderId) {
        return retailReturnOrderRepository.findByOriginalOrderIdOrderByReturnDateDesc(originalOrderId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailReturnOrder> findByOriginalOrderCode(String originalOrderCode) {
        return retailReturnOrderRepository.findByOriginalOrderCodeOrderByReturnDateDesc(originalOrderCode);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailReturnOrder> findByCustomerId(Long customerId) {
        return retailReturnOrderRepository.findByCustomerIdOrderByReturnDateDesc(customerId);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailReturnOrder> findByCustomerName(String customerName) {
        return retailReturnOrderRepository.findByCustomerNameContainingOrderByReturnDateDesc(customerName);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailReturnOrder> findByCustomerPhone(String customerPhone) {
        return retailReturnOrderRepository.findByCustomerPhoneOrderByReturnDateDesc(customerPhone);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailReturnOrder> findByReturnStatus(String returnStatus) {
        return retailReturnOrderRepository.findByReturnStatusOrderByReturnDateDesc(returnStatus);
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<RetailReturnOrder> findByReturnDateBetween(LocalDateTime startDate, LocalDateTime endDate) {
        return retailReturnOrderRepository.findByReturnDateBetween(startDate, endDate);
    }
    
    @Override
    public RetailReturnOrder approveReturnOrder(Long returnOrderId, String approverName, String remark) {
        Optional<RetailReturnOrder> orderOpt = retailReturnOrderRepository.findById(returnOrderId);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("退货订单不存在");
        }
        
        RetailReturnOrder order = orderOpt.get();
        order.setReturnStatus("Approved");
        order.setApprovedAt(LocalDateTime.now());
        order.setApproverName(approverName);
        order.setRemark(remark);
        order.setUpdatedAt(LocalDateTime.now());
        
        RetailReturnOrder savedOrder = retailReturnOrderRepository.save(order);
        
        // 创建审核通过跟踪记录
        createOrderTracking(returnOrderId, order.getReturnCode(), "Return", "Approved", 
                           "退货申请已审核通过", approverName, "审核通过" + (remark != null ? " - " + remark : ""));
        
        return savedOrder;
    }
    
    @Override
    public RetailReturnOrder rejectReturnOrder(Long returnOrderId, String reason, String approverName) {
        Optional<RetailReturnOrder> orderOpt = retailReturnOrderRepository.findById(returnOrderId);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("退货订单不存在");
        }
        
        RetailReturnOrder order = orderOpt.get();
        order.setReturnStatus("Rejected");
        order.setApprovedAt(LocalDateTime.now());
        order.setApproverName(approverName);
        order.setRemark(reason);
        order.setUpdatedAt(LocalDateTime.now());
        
        RetailReturnOrder savedOrder = retailReturnOrderRepository.save(order);
        
        // 创建审核拒绝跟踪记录
        createOrderTracking(returnOrderId, order.getReturnCode(), "Return", "Rejected", 
                           "退货申请已拒绝", approverName, "审核拒绝 - " + reason);
        
        return savedOrder;
    }
    
    @Override
    public RetailReturnOrder processReturnOrder(Long returnOrderId, String processorName) {
        return updateReturnStatus(returnOrderId, "Processing", processorName);
    }
    
    @Override
    public RetailReturnOrder completeReturnOrder(Long returnOrderId, String processorName) {
        Optional<RetailReturnOrder> orderOpt = retailReturnOrderRepository.findById(returnOrderId);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("退货订单不存在");
        }
        
        RetailReturnOrder order = orderOpt.get();
        order.setReturnStatus("Completed");
        order.setProcessedAt(LocalDateTime.now());
        order.setProcessorName(processorName);
        order.setUpdatedAt(LocalDateTime.now());
        
        RetailReturnOrder savedOrder = retailReturnOrderRepository.save(order);
        
        // 创建完成跟踪记录
        createOrderTracking(returnOrderId, order.getReturnCode(), "Return", "Completed", 
                           "退货处理已完成", processorName, "退货处理完成");
        
        return savedOrder;
    }
    
    @Override
    public RetailReturnOrder updateReturnStatus(Long returnOrderId, String status, String operatorName) {
        Optional<RetailReturnOrder> orderOpt = retailReturnOrderRepository.findById(returnOrderId);
        if (!orderOpt.isPresent()) {
            throw new RuntimeException("退货订单不存在");
        }
        
        RetailReturnOrder order = orderOpt.get();
        String oldStatus = order.getReturnStatus();
        order.setReturnStatus(status);
        order.setUpdatedAt(LocalDateTime.now());
        
        RetailReturnOrder savedOrder = retailReturnOrderRepository.save(order);
        
        // 创建状态变更跟踪记录
        String statusDescription = getStatusDescription(status);
        createOrderTracking(returnOrderId, order.getReturnCode(), "Return", status, 
                           statusDescription, operatorName, "状态从 " + oldStatus + " 变更为 " + status);
        
        return savedOrder;
    }
    
    @Override
    public void deleteById(Long id) {
        retailReturnOrderRepository.deleteById(id);
    }
    
    @Override
    @Transactional(readOnly = true)
    public Object getReturnStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 今日退货单数
        Long todayReturns = retailReturnOrderRepository.countTodayReturns();
        statistics.put("todayReturns", todayReturns);
        
        // 本月退货单数
        Long monthReturns = retailReturnOrderRepository.countMonthReturns();
        statistics.put("monthReturns", monthReturns);
        
        // 今日退货金额
        Double todayReturnAmount = retailReturnOrderRepository.sumTodayReturnAmount();
        statistics.put("todayReturnAmount", todayReturnAmount);
        
        // 本月退货金额
        Double monthReturnAmount = retailReturnOrderRepository.sumMonthReturnAmount();
        statistics.put("monthReturnAmount", monthReturnAmount);
        
        // 待审核退货单数
        List<RetailReturnOrder> pendingReturns = retailReturnOrderRepository.findPendingReturns();
        statistics.put("pendingReturns", pendingReturns.size());
        
        // 已审核退货单数
        List<RetailReturnOrder> approvedReturns = retailReturnOrderRepository.findApprovedReturns();
        statistics.put("approvedReturns", approvedReturns.size());
        
        // 处理中退货单数
        List<RetailReturnOrder> processingReturns = retailReturnOrderRepository.findProcessingReturns();
        statistics.put("processingReturns", processingReturns.size());
        
        // 已完成退货单数
        List<RetailReturnOrder> completedReturns = retailReturnOrderRepository.findCompletedReturns();
        statistics.put("completedReturns", completedReturns.size());
        
        return statistics;
    }
    
    @Override
    public String generateReturnCode() {
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        return "RRO" + dateStr + timeStr;
    }
    
    /**
     * 创建订单跟踪记录
     */
    private void createOrderTracking(Long orderId, String orderCode, String orderType, 
                                   String status, String statusDescription, String operatorName, String remark) {
        OrderTracking tracking = new OrderTracking();
        tracking.setOrderId(orderId);
        tracking.setStatusType(status);
        tracking.setStatusDescription(statusDescription);
        tracking.setOperatorName(operatorName);
        tracking.setRemark(remark);
        tracking.setTimestamp(LocalDateTime.now());
        
        orderTrackingRepository.save(tracking);
    }
    
    /**
     * 获取状态描述
     */
    private String getStatusDescription(String status) {
        switch (status) {
            case "Pending":
                return "待审核";
            case "Approved":
                return "已审核";
            case "Processing":
                return "处理中";
            case "Completed":
                return "已完成";
            case "Rejected":
                return "已拒绝";
            default:
                return status;
        }
    }
}
